package controller

import (
	"GoAdmin/models"
	"GoAdmin/utils"
	"GoAdmin/utils/cache"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"log"
	"net/http"
	"strings"
	"time"
)

func ApiSearchStudent(c *gin.Context) {

	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Methods", "GET")
	valid := validation.Validation{}
	valid.Required(c.PostForm("id_number"), "id_number").Message("身份证号获取失败")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	student, err := new(models.Student).GetOpenApiStudentDetail(c.PostForm("id_number"))
	if err != nil || student.StudentId == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询学员信息错误", "data": nil})
		return
	}
	//if student.Province != "370000" {
	//	c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询学员信息错误", "data": nil})
	//	return
	//}
	data := map[string]interface{}{
		"name":    student.Name,
		"phone":   student.Phone,
		"school":  student.JxJc,
		"carType": student.TrainType,
		"pic":     student.Pic,
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询成功", "data": data})
	return
}

type SimulatorLearnRecordFile struct {
	Phone     string `json:"phone" form:"phone"`
	Subject   string `json:"subject" form:"subject"`
	PhotoType string `json:"photo_type" form:"photo_type"`
	Photo     string `json:"photo" form:"photo"`
	PostTime  string `json:"post_time" form:"post_time"`
	UserId    string `json:"user_id" form:"user_id"`
}

// UploadSimulatorRecordFile upload simulator record file
func UploadSimulatorRecordFile(c *gin.Context) {
	req := new(SimulatorLearnRecordFile)
	if err := c.ShouldBind(req); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误", "data": nil})
		return
	}
	student, err := models.GetSimulatorStudentCacheData(req.Phone)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误", "data": nil})
		return
	}
	postTime, err := time.ParseInLocation("20060102150405", req.PostTime, time.Local)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误", "data": nil})
		return
	}
	water := map[string]string{
		"school_name":  fmt.Sprintf("%v", student["school_name"]),
		"date":         postTime.Format("2006-01-02 15:04:05"),
		"student_name": cast.ToString(student["student_name"]),
		"record_type":  "模拟器教学",
	}
	if req.Subject == "1" || req.Subject == "4" {
		water["record_type"] = "课堂教学"
	}
	fileURL, err := utils.WaterMarkTheory(water, req.Photo, req.Subject, fmt.Sprintf("%v", student["stu_code"]), req.PhotoType, "simulator", 10)
	if err != nil {
		log.Print(err)
		return
	}
	//log.Println(fileURL)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "上传成功", "data": fileURL})
	return
}

// SimulatorLearnRecord simulator learn record
type SimulatorLearnRecord struct {
	Phone     string              `json:"phone" form:"phone"`
	Subject   string              `json:"subject" form:"subject"`
	CarType   string              `json:"car_type" form:"car_type"`
	LearnType string              `json:"learn_type" form:"learn_type"`
	StartTime string              `json:"start_time" form:"start_time"`
	EndTime   string              `json:"end_time" form:"end_time"`
	Files     []map[string]string `json:"files" form:"files"`
	UserId    string              `json:"user_id" form:"user_id"`
}

// SimulatorStudentLogin student login
func SimulatorStudentLogin(c *gin.Context) {

	req := new(SimulatorLearnRecord)
	if err := c.ShouldBindJSON(req); err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误", "data": nil})
		return
	}
	log.Println(req)
	course := ""
	course += req.LearnType
	course += utils.CreatCarCode(req.CarType)
	course += req.Subject + "010000"
	if len(course) != 10 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "学时编号生成错误", "data": nil})
		return
	}
	student, err := models.GetSimulatorStudentCacheData(req.Phone)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "学员信息查询错误", "data": nil})
		return
	}

	rum, err := cache.SharedRedis().GetIncr(fmt.Sprintf("sn:%v", student["stu_code"]))
	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "学时编号查询错误", "data": nil})
		return
	}
	if cast.ToString(student["operation_status"]) == "11" || cast.ToString(student["operation_status"]) == "12" {
		rum = 80 + rum
	} else {
		rum = 2900 + rum
	}

	sn := cast.ToString(student["stu_code"]) + strings.Repeat("0", 5-len(fmt.Sprintf("%d", rum))) + fmt.Sprintf("%d", rum)
	id, err := models.StartUploadSimulatorRecord(student, sn, req.Subject, course, req.StartTime, req.EndTime, req.LearnType)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": error.Error(err), "data": nil})
		return
	}
	class := cast.ToInt(student["class"])
	for _, md := range req.Files {
		if _, err := models.StartUploadSimulatorFile(id, class, md); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "照片文件保存错误", "data": nil})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "上传成功", "data": nil})
	return
}
